<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>登录成功</title>
  <style>
    .user-info {
      position: absolute;
      top: 20px;
      right: 20px;
    }
    .user-info a {
      margin-left: 10px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    table, th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
    .pagination {
      margin-top: 10px;
    }
    .pagination button {
      margin-right: 5px;
      cursor: pointer;
    }
  </style>
</head>
<body>
<div class="user-info">
  你好，<span th:text="${userName}"></span>
  | <a href="/update-info">更改信息</a>
  | <a href="/logout">退出登录</a>
  | <a href="#" id="delete-account-btn">注销</a>
</div>

<h2>恭喜你，登录成功！</h2>
<p>欢迎回到系统。</p>

<div id="fruits-section">
  <h3>我最爱的水果</h3>
  <table id="fruit-table">
    <thead>
    <tr>
      <th>序号</th>
      <th>水果名称</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
  </table>

  <div class="pagination">
    <button id="prev-page">上一页</button>
    <span>第 <span id="current-page">1</span> 页 / 共 <span id="total-pages">0</span> 页</span>
    <button id="next-page">下一页</button>
  </div>

  <form id="add-fruit-form">
    <input type="text" id="fruit-name" placeholder="请输入水果名称" required>
    <button type="submit">添加</button>
  </form>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  let currentPage = 1;
  let totalPages = 0;

  // 加载水果列表（带分页）
  function loadFruits(page) {
    $.get(`/fruits?page=${page}&size=10`, function(response) {
      const fruits = response.records;
      totalPages = response.pages;
      currentPage = page;

      const $tableBody = $('#fruit-table tbody');
      $tableBody.empty();

      if (fruits.length > 0) {
        fruits.forEach((fruit, index) => {
          const row = `<tr><td>${response.current * response.size + index + 1 - response.size}</td><td>${fruit.fruitName}</td></tr>`;
          $tableBody.append(row);
        });
      } else {
        $tableBody.append('<tr><td colspan="2">您还没有添加任何水果。</td></tr>');
      }

      const displayTotalPages = totalPages > 0 ? totalPages : 1;

      $('#current-page').text(currentPage);
      $('#total-pages').text(displayTotalPages);
      $('#prev-page').prop('disabled', currentPage === 1);
      $('#next-page').prop('disabled', currentPage === totalPages);
    });
  }

  $(document).ready(function() {
    loadFruits(currentPage);

    $('#prev-page').click(function() {
      if (currentPage > 1) {
        loadFruits(currentPage - 1);
      }
    });

    $('#next-page').click(function() {
      if (currentPage < totalPages) {
        loadFruits(currentPage + 1);
      }
    });

    $('#add-fruit-form').submit(function(event) {
      event.preventDefault();
      const fruitName = $('#fruit-name').val();
      const newFruit = { fruitName: fruitName };

      $.ajax({
        url: '/fruits',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(newFruit),
        success: function(response) {
          alert(response.message);
          loadFruits(currentPage);
          $('#fruit-name').val('');
        },
        error: function(xhr) {
          const errorMessage = JSON.parse(xhr.responseText).message;
          alert(errorMessage);
        }
      });
    });

    // 独立处理注销按钮的点击事件
    $('#delete-account-btn').click(function(event) {
      event.preventDefault(); // 阻止默认的超链接行为
      if (confirm('确定要注销账户吗？此操作不可逆！')) {
        $.ajax({
          url: '/user/delete-account', // 确保 URL 正确，带上 /user
          type: 'DELETE', // 使用 DELETE 方法
          success: function(response) {
            alert('账户已注销，即将跳转到登录页。');
            window.location.href = '/logout'; // 注销成功后跳转到退出登录页面
          },
          error: function(xhr) {
            alert('注销失败：' + xhr.responseText);
          }
        });
      }
    });
  });
</script>
</body>
</html>